package com.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.entity.User;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Scanner;

/**
 * @author zhr
 */
@RestController
public class UserController {
    private static final String PROVIDER_APP_NAME = "demo-eureka-client-consumer-1";
    private static final String DEMO_1_URL = "http://localhost:5002/";
    private final RestTemplate restTemplate;
    private final DiscoveryClient discoveryClient;

    public UserController(RestTemplate restTemplate, DiscoveryClient discoveryClient) {
        this.restTemplate = restTemplate;
        this.discoveryClient = discoveryClient;
    }

    @GetMapping("user/list")
    public Page<User> getList() {
        ResponseEntity<Page> forEntity = restTemplate.getForEntity(DEMO_1_URL + "user/list", Page.class);
        return forEntity.getBody();
    }

    @GetMapping("user/list-1")
    public Page<User> getListByDiscoveryClient() {
        String baseUrl = "";
        List<String> services = discoveryClient.getServices();
        for (int i = 0; i < services.size(); i++) {
            String serviceName = services.get(i);
            if (PROVIDER_APP_NAME.equalsIgnoreCase(serviceName)) {
                List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
                if (CollectionUtils.isEmpty(instances)){
                    System.err.println("no instance ");
                }else {
                    baseUrl = instances.get(0).getUri().toString();
                }
                break;
            }
        }
        ResponseEntity<Page> forEntity = restTemplate.getForEntity(baseUrl + "/user/list",
                Page.class);
        return forEntity.getBody();
    }
}
